<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="商家ID" prop="merchantId">
        <el-input
          v-model="queryParams.merchantId"
          placeholder="请输入商家ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item label="跳转链接" prop="linkUrl">
        <el-input
          v-model="queryParams.linkUrl"
          placeholder="请输入跳转链接"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="副标题" prop="subtitle">
        <el-input
          v-model="queryParams.subtitle"
          placeholder="请输入副标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="顺序" prop="sortOrder">
        <el-input
          v-model="queryParams.sortOrder"
          placeholder="请输入顺序"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="轮播图类型" prop="bannerType">
        <el-select
          v-model="queryParams.bannerType"
          placeholder="请选择轮播图类型"
          clearable
        >
          <el-option
            v-for="dict in banner_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否启用" prop="isEnabled">
        <el-select
          v-model="queryParams.isEnabled"
          placeholder="请选择是否启用"
          clearable
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in wdm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:bannerInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:bannerInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:bannerInfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:bannerInfo:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="bannerInfoList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="55"
        align="center"
        prop="bannerId"
      />
      <el-table-column label="商家" align="center" prop="merchantId" />

      <!-- <el-table-column
        label="效果图"
        align="center"
        prop="imageUrl"
        width="100"
      >
        <template #default="scope">
          <div class="image-container">
            <image-preview
              :src="scope.row.imageUrl"
              :width="50"
              :height="50"
              :lazy="true"
            />
            <div class="image-info" v-if="scope.row.imageSize">
              <el-tag size="small" type="info">
                {{ formatFileSize(scope.row.imageSize) }}
              </el-tag>
            </div>
          </div>
        </template>
      </el-table-column> -->

      <el-table-column
        label="效果图"
        align="center"
        prop="imageUrl"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
        </template>
      </el-table-column>

      <!-- <el-table-column label="跳转链接" align="center" prop="linkUrl" /> -->

      <el-table-column
        label="标题"
        align="center"
        min-width="150"
        prop="title"
      />
      <!-- <el-table-column label="副标题" align="center" prop="subtitle" /> -->
      <el-table-column label="顺序" align="center" prop="sortOrder" />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="轮播图类型"
        min-width="120"
        align="center"
        prop="bannerType"
      >
        <template #default="scope">
          <dict-tag :options="banner_type" :value="scope.row.bannerType" />
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center" prop="isEnabled">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isEnabled" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        min-width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:bannerInfo:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:bannerInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轮播图信息对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" append-to-body>
      <el-form
        ref="bannerInfoRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商家" prop="merchantId">
          <el-input v-model="form.merchantId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="图片地址" prop="imageUrl">
          <!-- <image-upload v-model="form.imageUrl" /> -->
          <image-upload v-model="form.imageUrl" :auto-upload="false" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入跳转链接" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="顺序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入顺序" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择展示开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择展示结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" label-width="80px" prop="bannerType">
          <el-select v-model="form.bannerType" placeholder="请选择轮播图类型">
            <el-option
              v-for="dict in banner_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用" prop="isEnabled">
          <el-select v-model="form.isEnabled" placeholder="请选择是否启用">
            <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除" prop="delFlag">
          <el-radio-group v-model="form.delFlag">
            <el-radio
              v-for="dict in del_flag"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BannerInfo">
import {
  listBannerInfo,
  getBannerInfo,
  delBannerInfo,
  addBannerInfo,
  updateBannerInfo,
} from "@/api/ruoyi/bannerInfo";

const { proxy } = getCurrentInstance();
const { wdm_status, sys_yes_no, banner_type, del_flag } = proxy.useDict(
  "wdm_status",
  "sys_yes_no",
  "banner_type",
  "del_flag"
);

const bannerInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merchantId: null,
    imageUrl: null,
    linkUrl: null,
    title: null,
    subtitle: null,
    sortOrder: null,
    startTime: null,
    endTime: null,
    bannerType: null,
    isEnabled: null,
    status: null,
  },
  rules: {
    merchantId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询轮播图信息列表 */
function getList() {
  loading.value = true;
  listBannerInfo(queryParams.value).then((response) => {
    // bannerInfoList.value = response.rows
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    bannerInfoList.value = response.rows.filter((item) => item.delFlag !== "2");
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    bannerId: null,
    merchantId: null,
    imageUrl: null,
    linkUrl: null,
    title: null,
    subtitle: null,
    sortOrder: null,
    startTime: null,
    endTime: null,
    bannerType: null,
    isEnabled: null,
    status: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("bannerInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.bannerId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加轮播图信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _bannerId = row.bannerId || ids.value;
  getBannerInfo(_bannerId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改轮播图信息";
  });
}

/**
 * 智能图片压缩函数
 * @param {string} imageUrl - 原始图片URL或base64数据
 * @param {Object} options - 压缩选项
 * @returns {Promise<string>} - 压缩后的图片数据URL
 */
function smartCompressImage(imageUrl, options = {}) {
  return new Promise((resolve, reject) => {
    if (!imageUrl || !imageUrl.startsWith("data:image")) {
      resolve(imageUrl);
      return;
    }

    const {
      maxWidth = 1200,
      maxHeight = 800,
      quality = 0.6,
      format = "webp",
    } = options;

    const img = new Image();
    img.crossOrigin = "Anonymous";

    img.onload = function () {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      // 计算目标尺寸，保持宽高比
      let { width, height } = calculateTargetSize(
        img.width,
        img.height,
        maxWidth,
        maxHeight
      );

      canvas.width = width;
      canvas.height = height;

      // 使用高质量缩放
      ctx.imageSmoothingQuality = "high";
      ctx.drawImage(img, 0, 0, width, height);

      try {
        const mimeType = getMimeType(format);
        const compressedDataUrl = canvas.toDataURL(mimeType, quality);

        logCompressionStats(imageUrl, compressedDataUrl, {
          originalSize: { width: img.width, height: img.height },
          compressedSize: { width, height },
          format,
        });

        resolve(compressedDataUrl);
      } catch (e) {
        console.warn(`${format} not supported, falling back to JPEG`, e);
        const jpegDataUrl = canvas.toDataURL("image/jpeg", quality);
        resolve(jpegDataUrl);
      }
    };

    img.onerror = reject;
    img.src = imageUrl;
  });
}

/** 计算目标尺寸 */
function calculateTargetSize(
  originalWidth,
  originalHeight,
  maxWidth,
  maxHeight
) {
  let width = originalWidth;
  let height = originalHeight;

  if (width > maxWidth) {
    height = (height * maxWidth) / width;
    width = maxWidth;
  }

  if (height > maxHeight) {
    width = (width * maxHeight) / height;
    height = maxHeight;
  }

  return { width: Math.round(width), height: Math.round(height) };
}

/** 获取MIME类型 */
function getMimeType(format) {
  const mimeTypes = {
    webp: "image/webp",
    jpeg: "image/jpeg",
    png: "image/png",
  };
  return mimeTypes[format] || "image/jpeg";
}

/** 记录压缩统计 */
function logCompressionStats(originalUrl, compressedUrl, metadata) {
  const originalSize = Math.round((originalUrl.length * 0.75) / 1024);
  const compressedSize = Math.round((compressedUrl.length * 0.75) / 1024);
  const compressionRatio = ((1 - compressedSize / originalSize) * 100).toFixed(
    1
  );

  console.log(
    `[图片压缩] 原始: ${metadata.originalSize.width}x${metadata.originalSize.height} (~${originalSize}KB)`
  );
  console.log(
    `[图片压缩] 压缩后: ${metadata.compressedSize.width}x${metadata.compressedSize.height} (~${compressedSize}KB)`
  );
  console.log(
    `[图片压缩] 压缩率: ${compressionRatio}%, 格式: ${metadata.format}`
  );
}

// =======================================

/**
 * 图片分割函数 - 将大图分割成多个小块
 * @param {string} imageUrl - 原始图片URL
 * @param {number} chunkSize - 每块的大小（像素）
 * @returns {Promise<Array>} - 分割后的图片块数组
 */
async function splitImageIntoChunks(imageUrl, chunkSize = 512) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "Anonymous";

    img.onload = function () {
      const chunks = [];
      const rows = Math.ceil(img.height / chunkSize);
      const cols = Math.ceil(img.width / chunkSize);

      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = chunkSize;
      canvas.height = chunkSize;

      // 分割图片
      for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
          const x = col * chunkSize;
          const y = row * chunkSize;
          const width = Math.min(chunkSize, img.width - x);
          const height = Math.min(chunkSize, img.height - y);

          // 清空canvas
          ctx.clearRect(0, 0, chunkSize, chunkSize);

          // 绘制当前块
          ctx.drawImage(img, x, y, width, height, 0, 0, width, height);

          const chunkDataUrl = canvas.toDataURL("image/webp", 0.7);
          chunks.push({
            row,
            col,
            x,
            y,
            width,
            height,
            dataUrl: chunkDataUrl,
            totalRows: rows,
            totalCols: cols,
          });
        }
      }

      console.log(
        `[图片分割] 原图: ${img.width}x${img.height}, 分割为: ${rows}x${cols} 共${chunks.length}块`
      );
      resolve(chunks);
    };

    img.onerror = reject;
    img.src = imageUrl;
  });
}

/**
 * 合并分割的图片块（在小程序端使用）
 * @param {Array} chunks - 图片块数组
 * @param {number} originalWidth - 原图宽度
 * @param {number} originalHeight - 原图高度
 * @returns {string} - 合并后的图片URL
 */
function mergeImageChunks(chunks, originalWidth, originalHeight) {
  // 这个函数通常在小程序端执行
  // 这里提供伪代码逻辑
  console.log(`[图片合并] 开始合并 ${chunks.length} 个图片块`);

  // 在小程序中可以使用canvas进行合并
  // const ctx = wx.createCanvasContext('mergeCanvas');
  // chunks.forEach(chunk => {
  //   ctx.drawImage(chunk.tempPath, chunk.x, chunk.y, chunk.width, chunk.height);
  // });
  // ctx.draw();

  return "merged_image_url";
}

/**
 * 压缩图片并转换为WebP格式
 * @param {string} imageUrl - 原始图片URL或base64数据
 * @param {number} [quality=0.7] - 压缩质量(0-1)
 * @returns {Promise<string>} - 返回WebP格式的图片数据URL
 */
function compressImageToWebP(imageUrl, quality = 0.7) {
  return new Promise((resolve, reject) => {
    // 如果不是base64图片数据，直接返回原URL
    if (!imageUrl || !imageUrl.startsWith("data:image")) {
      resolve(imageUrl);
      return;
    }

    const img = new Image();
    img.crossOrigin = "Anonymous"; // 处理跨域图片

    img.onload = function () {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      // 设置目标尺寸（保持原图比例）
      let targetWidth = img.width;
      let targetHeight = img.height;

      // 如果图片很大，缩小尺寸（可调整最大尺寸）
      const maxSize = 1920;
      if (img.width > maxSize || img.height > maxSize) {
        if (img.width > img.height) {
          targetWidth = maxSize;
          targetHeight = (img.height * maxSize) / img.width;
        } else {
          targetHeight = maxSize;
          targetWidth = (img.width * maxSize) / img.height;
        }
      }

      canvas.width = targetWidth;
      canvas.height = targetHeight;

      // 绘制图片到canvas
      ctx.drawImage(img, 0, 0, targetWidth, targetHeight);

      try {
        // 尝试转换为WebP格式
        const webpDataUrl = canvas.toDataURL("image/webp", quality);
        // 日志
        console.log(
          `[图片压缩] 原始尺寸: ${img.width}x${img.height}, 压缩后尺寸: ${targetWidth}x${targetHeight}`
        );
        console.log(
          `[图片压缩] 原始大小: ~${Math.round(
            (imageUrl.length * 0.75) / 1024
          )}KB, 压缩后大小: ~${Math.round(
            (webpDataUrl.length * 0.75) / 1024
          )}KB`
        );

        resolve(webpDataUrl);
      } catch (e) {
        // 如果浏览器不支持WebP，回退到JPEG
        console.warn("WebP not supported, falling back to JPEG", e);
        const jpegDataUrl = canvas.toDataURL("image/jpeg", quality);
        resolve(jpegDataUrl);
      }
    };

    img.onerror = reject;
    img.src = imageUrl;
  });
}

/** 提交按钮 */
/** 智能图片处理并提交 */
async function submitForm() {
  proxy.$refs["bannerInfoRef"].validate(async (valid) => {
    if (!valid) return;

    try {
      let processedImageUrl = form.value.imageUrl;

      // 处理新上传的图片
      if (processedImageUrl && processedImageUrl.startsWith("data:image")) {
        const loadingInstance = proxy.$modal.loading("正在优化图片，请稍候...");

        try {
          // 根据图片大小选择处理策略
          const imageSize = calculateImageSize(processedImageUrl);

          if (imageSize > 500 * 1024) {
            // 大于500KB的图片使用分割策略
            console.log("检测到大图，启用分割策略");
            processedImageUrl = await processLargeImage(processedImageUrl);
          } else {
            // 普通图片使用压缩策略
            processedImageUrl = await smartCompressImage(processedImageUrl, {
              maxWidth: 1200,
              maxHeight: 800,
              quality: 0.6,
              format: "webp",
            });
          }

          // 上传到服务器
          const uploadedUrl = await uploadProcessedImage(processedImageUrl);
          form.value.imageUrl = uploadedUrl;
        } finally {
          loadingInstance.close();
        }
      }

      // 提交表单数据
      await submitBannerData();
    } catch (error) {
      console.error("表单提交失败:", error);
      proxy.$modal.msgError("操作失败，请重试");
    }
  });
}

/** 处理大图（分割+压缩） */
async function processLargeImage(imageUrl) {
  // 先压缩到合理大小
  const compressedImage = await smartCompressImage(imageUrl, {
    maxWidth: 2000,
    maxHeight: 2000,
    quality: 0.8,
    format: "webp",
  });

  // 如果压缩后仍然很大，考虑分割
  const compressedSize = calculateImageSize(compressedImage);
  if (compressedSize > 300 * 1024) {
    console.log("压缩后仍然较大，启用分割");
    // 在实际项目中，这里可以调用分割函数
    // const chunks = await splitImageIntoChunks(compressedImage, 512);
    // 上传所有块并记录元数据
    // form.value.imageChunks = chunks;
  }

  return compressedImage;
}

/** 计算图片大小（KB） */
function calculateImageSize(dataUrl) {
  if (!dataUrl) return 0;
  // 估算base64数据大小
  return Math.round((dataUrl.length * 0.75) / 1024);
}

/** 上传处理后的图片 */
async function uploadProcessedImage(processedImageUrl) {
  const formData = new FormData();
  const blob = await (await fetch(processedImageUrl)).blob();

  // 根据blob类型确定文件扩展名
  const extension = blob.type.includes("webp") ? "webp" : "jpg";
  formData.append("file", blob, `banner_${Date.now()}.${extension}`);

  const uploadRes = await new Promise((resolve, reject) => {
    proxy.upload(formData, "/common/upload", {
      onSuccess: resolve,
      onError: reject,
    });
  });

  return uploadRes.fileName ? `/profile${uploadRes.fileName}` : uploadRes.url;
}

/** 提交轮播图数据 */
async function submitBannerData() {
  const action = form.value.bannerId
    ? () => updateBannerInfo(form.value)
    : () => addBannerInfo(form.value);

  await action();
  proxy.$modal.msgSuccess(form.value.bannerId ? "修改成功" : "新增成功");
  open.value = false;
  getList();
}

/** 格式化文件大小 */
function formatFileSize(bytes) {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}

/** 图片质量预设 */
const QUALITY_PRESETS = {
  low: { quality: 0.4, maxWidth: 800, maxHeight: 600 },
  medium: { quality: 0.6, maxWidth: 1200, maxHeight: 800 },
  high: { quality: 0.8, maxWidth: 1600, maxHeight: 1200 },
};

// ====================================================================

// function submitForm() {
//   proxy.$refs["bannerInfoRef"].validate(valid => {
//     if (valid) {
//       if (form.value.bannerId != null) {
//         updateBannerInfo(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addBannerInfo(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 提交按钮 */
// async function submitForm() {
//   proxy.$refs["bannerInfoRef"].validate(async (valid) => {
//     if (valid) {
//       let shouldProcessImage = false;
//       let originalImageUrl = null;
//       let processedImageUrl = null; // 修正：统一使用processedImageUrl变量名

//       // 检查是否需要处理图片（新上传的图片）
//       if (form.value.imageUrl && form.value.imageUrl.startsWith("data:image")) {
//         shouldProcessImage = true;
//         originalImageUrl = form.value.imageUrl;

//         try {
//           // 显示加载提示
//           const loading = proxy.$modal.loading("正在优化图片，请稍候...");

//           // 压缩图片并转换为WebP
//           processedImageUrl = await compressImageToWebP(
//             form.value.imageUrl,
//             0.6
//           ); // 修正：赋值给processedImageUrl

//           // 更新表单中的图片URL
//           form.value.imageUrl = processedImageUrl; // 修正：使用正确的变量

//           // 关闭加载提示
//           loading.close();
//         } catch (error) {
//           console.error("图片处理失败:", error);
//           proxy.$modal.msgError("图片处理失败，请重试");
//           return;
//         }
//       }

//       // ★ 修正：检查processedImageUrl是否存在
//       if (processedImageUrl) {
//         try {
//           const formData = new FormData();
//           const blob = await (await fetch(processedImageUrl)).blob();

//           // ★ 修正：使用.webp扩展名
//           formData.append("file", blob, "banner_" + Date.now() + ".webp");

//           // ★ 修正：使用proxy.upload直接上传
//           const uploadRes = await new Promise((resolve, reject) => {
//             proxy.upload(formData, "/common/upload", {
//               onSuccess: resolve,
//               onError: reject,
//             });
//           });

//           // ★ 修正：确保获取到正确的URL
//           form.value.imageUrl = uploadRes.fileName
//             ? `/profile${uploadRes.fileName}`
//             : uploadRes.url;
//         } catch (e) {
//           console.error("上传失败", e);
//           proxy.$modal.msgError("图片上传失败");
//           return;
//         }
//       }

//       // 提交表单
//       const submitAction = form.value.bannerId
//         ? () => updateBannerInfo(form.value)
//         : () => addBannerInfo(form.value);

//       try {
//         await submitAction();
//         proxy.$modal.msgSuccess(form.value.bannerId ? "修改成功" : "新增成功");
//         open.value = false;
//         getList();
//       } catch (error) {
//         console.error("提交失败:", error);

//         // 如果图片处理过且提交失败，恢复原始图片
//         if (shouldProcessImage) {
//           form.value.imageUrl = originalImageUrl;
//         }

//         proxy.$modal.msgError("操作失败，请重试");
//       }
//     }
//   });
// }

/** 手动上传文件到服务器 */
// async function uploadFile(formData) {
//   // ★ 修正：使用若依框架的标准上传方法
//   return new Promise((resolve, reject) => {
//     proxy.upload(formData, "/common/upload", {
//       onSuccess: (res) => resolve(res),
//       onError: (err) => reject(err),
//     });
//   });
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _bannerIds = row.bannerId || ids.value;
  proxy.$modal
    .confirm('是否确认删除轮播图信息编号为"' + _bannerIds + '"的数据项？')
    .then(function () {
      return delBannerInfo(_bannerIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/bannerInfo/export",
    {
      ...queryParams.value,
    },
    `bannerInfo_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 图片处理时的加载样式 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8) !important;
}

.el-loading-text {
  font-size: 16px !important;
  color: #606266 !important;
}

/* 图片处理时的加载样式 */
.image-container {
  position: relative;
  display: inline-block;
}

.image-info {
  margin-top: 4px;
}

/* 加载动画 */
.image-loading {
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

/* 响应式图片 */
.responsive-image {
  max-width: 100%;
  height: auto;
  object-fit: cover;
}

/* 压缩进度提示 */
.compression-progress {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 8px;
  font-size: 12px;
}
</style>
